<!DOCTYPE html>
<html>

<head>
    <title>Vector tiles</title>
    <script src="ol.js"></script>
    <link rel="stylesheet" href="ol.css">
    <style>
        html,
        body {
            font-family: sans-serif;
            width: 100%;
        }

        .map {
            height: 500px;
            width: 100%;
        }
    </style>
</head>

<body>
    <h3>Mapbox Protobuf - raster tiles</h3>
    <div id="Map" class="map"></div>
    <script>
        var mymap;

        function initMap() {

            mymap = new ol.Map({
                target: "Map",
                layers: [],
                view: new ol.View({
                    center: ol.proj.fromLonLat([116.6584, 35.3766]),// 4326坐标转3857坐标
                    zoom: 4.7,
                    maxZoom: 9,
                    minZoom: 7,
                    projection: 'EPSG:3857',
                }),
            });

            mymap.on("singleclick", function (evt) {
                const coordinate = evt.coordinate;
                setPoint(coordinate); //直接是3857坐标
            });

        }

        //添加定位图标
        function setPoint(local) {
            console.log('local==', local)
            var pointLayer = new ol.Feature({
                title: 'point点',
                geometry: new ol.geom.Point(local),
            });

            pointLayer.setStyle(
                new ol.style.Style({
                    image: new ol.style.Icon({
                        radius: 4,
                        src: 'marker.png'
                    }),

                })
            );
            var vectorSource = new ol.source.Vector({
                features: [pointLayer]
            });

            var vectorLayer = new ol.layer.Vector({
                source: vectorSource
            });

            mymap.addLayer(vectorLayer);

        }


        function showWMTSLayer(url, layerId, layerName, zIndex) {
            return new Promise((resolve) => {
                const self = this;
                // 首先设置好WMTS瓦片地图的瓦片坐标系
                const projection = ol.proj.get('EPSG:3857');          // 获取web墨卡托投影坐标系
                const projectionExtent = projection.getExtent();      // web墨卡托投影坐标系的四至范围
                const width = ol.extent.getWidth(projectionExtent);   // web墨卡托投影坐标系的水平宽度，单位米
                const resolutions = [];                               // 瓦片地图分辨率
                const matrixIds = [];    //矩阵ID

                for (let z = 7; z < 10; z++) {
                    resolutions[z] = width / (256 * Math.pow(2, z + 1));//注意这里的分辨率需要根据geoserver切片参数对应
                    matrixIds[z] = "EPSG:3857:" + z;              // 注意这里的matrixId的格式为EPSG:4326:z

                }
                const wmtsTileGrid = new ol.tilegrid.WMTS({
                    origin: ol.extent.getTopLeft(projectionExtent), // 原点（左上角）
                    resolutions: resolutions,                       // 瓦片地图分辨率
                    matrixIds: matrixIds,                           // 矩阵ID，就是瓦片坐标系z维度各个层级的标识
                });

                // WMTS数据源与地图
                const wmtsSource = new ol.source.WMTS({
                    url: url,
                    layer: layerName,                   // 图层名
                    matrixSet: 'EPSG:3857',           // 投影坐标系参数矩阵集
                    format: 'image/png',                // 图片格式
                    projection: projection,             // 投影坐标系
                    // 投影坐标系
                    tileGrid: wmtsTileGrid
                });


                const xmlUrl = wmtsSource.getUrls()[0] + "?service=WMTS&version=1.0.0&request=GetCapabilities";
                console.log(xmlUrl)
                let extent = [];
                const parser = new ol.format.WMTSCapabilities();
                fetch(xmlUrl)
                    .then(function (response) {
                        return response.text();
                    })
                    .then(function (text) {

                        const result = parser.read(text);
                        const options = ol.source.WMTS.optionsFromCapabilities(result, {
                            layer: layerId,
                            matrixSet: 'EPSG:3857',
                        });

                        mymap.addLayer(new ol.layer.Tile({
                            opacity: 1,
                            source: new ol.source.WMTS(options),
                        }));


                        resolve(true)
                    });
            })
        }

        //初始化地图
        initMap();

        //加载底图
        showWMTSLayer('http://192.168.2.27:8600/geoserver/jxGIS/gwc/service/wmts', 'jining7', 'jining7', 7);
    </script>
</body>

</html>